// packageD/o2o/recommendtext/recommendtext.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    language: "",
    store_id: "",
    kwd: "",
    page: 1,
    total_page: 1,
    datas: "",
    chooseGoods: [],
    result: [],
    historicalRecord: [],
    inputShow: false,
    showPopup: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      store_id: options.store_id,
      show_num: options.show_num,
      datas: []
    });
    this.getStoreInfo();
  },
  inpbtn(e) {
    let getData = wx.getStorageSync('introduceGoodRecords_') ? JSON.parse(wx.getStorageSync('introduceGoodRecords_')) : [];
    let historicalRecord = [...getData,e.detail.value];
    historicalRecord = [...new Set(Array.from([...historicalRecord].filter(Boolean)))];
    this.setData({
      kwd: e.detail.value,
      page: 1,
      datas: [],
      historicalRecord
    });
    wx.setStorageSync("introduceGoodRecords_", JSON.stringify(historicalRecord));
    this.getStoreInfo();
  },
  add() {
    console.log(this.data.result);
    let json = {
      store_id: this.data.store_id,
      choose_goods: this.data.result,
    };
    this.tapPush(json);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({ language: language.en });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.page >= this.data.total_page) {
      wx.showToast({
        title: "没有更多",
        icon: "none",
        duration: 1500,
      });
    } else {
      let pageAge = this.data.page + 1;
      this.setData({
        page: pageAge,
      });
      this.getStoreInfo();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  getStoreInfo() {
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.store-cashier.frontend.store.goods.get-goods-by-kwd"
    );
    app._postNetWork({
      url: urlStr,
      data: {
        store_id: that.data.store_id,
        kwd: this.data.kwd,
        page: this.data.page,
      },
      success: function (resdata) {
        var res = resdata.data;
        console.log(res);
        if (res.result == 1) {
          let newDatas = that.data.datas.concat(res.data.data);
            for(let item of that.data.result) {
              for(let citem of newDatas) {
                if(item == citem.id) {
                  citem.isAdd = true
                }
              }
            }
          that.setData({
            datas: newDatas,
            total_page: res.data.last_page,
            last_page: res.data.last_page,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  tapPush(json) {
    let urlStr = app.getNetAddresss(
      "plugin.nearby-store-goods.frontend.controllers.goods.index"
    );
    app._postNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        console.log(res);
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  // 选中商品
  clickAdd(item) {
    let index = item.currentTarget.dataset.index;

    let newDatas = this.data.datas;
    newDatas[index].isAdd = true;
    let newChooseGoods = newDatas.filter(item  => item.isAdd);
    newChooseGoods  = this.reduceData([...this.data.chooseGoods,...newChooseGoods]);
    let newResult = newChooseGoods.map(citem => citem.id);
    this.setData({
      datas: newDatas,
      chooseGoods: newChooseGoods,
      result: newResult
    })
  },
  // 删除商品
  clickDel(item) {
    let id = item.currentTarget.dataset.id;
    let index = item.currentTarget.dataset.index;
    
    let newDatas = this.data.datas;
    newDatas[index].isAdd = false;
    let newChooseGoods  = this.data.chooseGoods;
    let index_ = ""
    for(let [key , item] of newChooseGoods.entries()) {
      if(item.id == id) {
        index_ = key;
      }
    }
    newChooseGoods.splice(index_,1);
    let newResult = newChooseGoods.map(citem => citem.id);
    this.setData({
      datas: newDatas,
      chooseGoods: newChooseGoods,
      result: newResult
    })
  },
  // 删除选中的数据
  delChooseGoods(item) {
    let id = item.currentTarget.dataset.id;
    let index = item.currentTarget.dataset.index;

    let newDatas = this.data.datas;
    let newChooseGoods = this.data.chooseGoods;
    newChooseGoods.splice(index,1);
    for(let [index_ , item] of newDatas.entries()) {
      if(item.id == id) {
        newDatas[index_].isAdd = false;
      }
    }
    let newResult = newChooseGoods.map(citem => citem.id);
    this.setData({
      datas: newDatas,
      chooseGoods: newChooseGoods,
      result: newResult
    })
  },
  // 清空选中数据
  clearChooseGoods() {
    let newDatas = this.data.datas;
    for(let [index_ , item] of newDatas.entries()) {
      newDatas[index_].isAdd = false;
    }
    this.setData({
      datas: newDatas,
      chooseGoods: [],
      result: []
    })
  },
  // 过滤重复数据
  reduceData(person) {
    let obj = {};
    let peon = person.reduce((cur,next) => {
        obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
        return cur;
    },[]) //设置cur默认类型为数组，并且初始值为空的数组
    return peon
  },
  searchFocusr() {
    let getData = wx.getStorageSync('introduceGoodRecords_') ? JSON.parse(wx.getStorageSync('introduceGoodRecords_')) : [];
    this.setData({
      historicalRecord: getData
    });
    this.setData({
      inputShow: true
    })
  },
  searchBlur() {
    this.setData({
      inputShow: false
    })
  },
  searchHistoricalRecord(e) {
    this.setData({
      kwd: e.currentTarget.dataset.value,
      page: 1,
      datas: []
    });
    this.getStoreInfo();
  },
  delHistoricalRecord(e) {
    let historicalRecord = this.data.historicalRecord
    historicalRecord.splice(e.currentTarget.dataset.index,1);
    this.setData({
      historicalRecord
    })
    wx.setStorageSync("introduceGoodRecords_", JSON.stringify(historicalRecord));
  },
  clearHistoryData() {
    this.setData({
      historicalRecord: []
    })
    wx.setStorageSync("introduceGoodRecords_", JSON.stringify([]));
  },
  openPopup() {
    this.setData({
      showPopup: true,
    })
  },
  onClose() {
    this.setData({
      showPopup: false,
    })
  },
});
